package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;
    @Override
    public R<Employee> login(Employee employee) {
        Employee dbEmployee = employeeMapper.login(employee);
        if(dbEmployee==null){
            return R.error("用户名不存在");
        }

//        String md5Password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
//        if(!dbEmployee.getPassword().equals(md5Password)){
//            return R.error("密码错误");
//        }
        if(!dbEmployee.getPassword().equals(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()))){
            return R.error("密码错误");
        }

        if(dbEmployee.getStatus()==0){

            return R.error("该用户已经被禁用");
        }

        return R.success(dbEmployee);
    }

    @Override
    public void save(Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeMapper.save(employee);
    }

    @Override
    public Page<Employee> selectByPage(int page, int pageSize, String name) {
        //1. 设置当前页与页面大小
        PageHelper.startPage(page,pageSize);
        //2. 查询数据
        List<Employee> employeeList = employeeMapper.selectByPage(name);
        //3. 创建PageINfo对象，把list集合传入
        PageInfo<Employee> pageInfo = new PageInfo(employeeList);
        //4. 把pageinfo的信息转移到Page对象
        Page<Employee> resultPage = new Page<>(pageInfo.getList(),pageInfo.getPageNum(),pageInfo.getPageSize(),pageInfo.getTotal());
        return resultPage;
    }

    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    @Override
    public R<Employee> findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return R.success(employee);
    }
}
